<template>
    <div class="chat-container">
      <div v-if="messages.length == 0" class="welcome-message">
      <h3 class="welcome-title">我是数据分析成果大脑，很高兴见到您！</h3>
      <h5 class="welcome-subtitle">我可以帮你数据智能分析、深度挖掘、为灾害预测、应急响应和调度规划提供建议和技术支持，请把你的任务交给我吧~</h5>
    </div>
      <el-scrollbar ref="scroll" class="messages-box">
        <div v-for="(msg, index) in messages" 
             :key="index"
             :class="['message', msg.role]">
          <el-card shadow="hover">
            <div class="message-header">
              <el-tag :type="msg.role === 'user' ? 'primary' : 'success'">
                {{ msg.role === 'user' ? '您' : '助手' }}
              </el-tag>
            </div>
            <formatted-content :content="msg.content" />
          </el-card>
        </div>
        <div v-if="loading" class="loading-indicator">
          <i class="el-icon-loading"></i> 正在生成...
        </div>
      </el-scrollbar>
      <div class="input-area">
  <el-row type="flex" align="middle">
    <!-- 输入框区域 -->
    <el-col :span="24">
      <div class="input-with-buttons">
        <el-input
          v-model="inputText"
          type="textarea"
          :rows="3"
          placeholder="输入您的问题..."
          @keydown.enter.native.prevent="sendMessage"
          class="input-box"
        />
        <!-- 按钮容器 -->
        <div class="inner-buttons">
          <el-button
            type="primary"
            :loading="loading"
            @click="sendMessage"
            size="small"
            class="send-btn">
            发送
          </el-button>
          <el-button
            type="danger"
            @click="stopMessage"
            size="small"
            class="stop-btn">
            停止
          </el-button>
        </div>
      </div>
    </el-col>
  </el-row>
</div>
    </div>
  </template>
  
  <script lang="ts">
import { Component, Mixins, Ref, Prop } from 'vue-property-decorator';
import LocalStreamHandler from '@/utils/LocalStreamHandler'; // 修改为本地流处理器
import FormattedContent from '@/views/app/components/FormattedContent.vue';

interface ChatMessage {
  role: string;
  content: string;
  metadata?: {
    usage?: any;
    resources?: any[];
  };
  files?: Array<{
    type: string;
    url: string;
  }>;
}

@Component({
  components: { FormattedContent }
})
export default class ChatWindow extends Mixins(LocalStreamHandler) {
  @Ref() readonly scroll!: any;
  @Prop() answerMap!: any[];

  private streamDataHandler!: (chunk: string) => void;
  private streamMetaHandler!: (meta: any) => void;
  private streamFileHandler!: (file: any) => void;
  
  messages: ChatMessage[] = [];
  inputText = '';
  loading = false;
  currentAnswer = '';
  data: any = null;

  async sendMessage() {
    if (!this.inputText.trim() || this.loading) return;

    this.loading = true;
    this.messages.push({ 
      role: 'user', 
      content: this.inputText,
      files: this.data ? [{ type: 'data', url: '#' }] : undefined 
    });
    
    // 新增助手消息结构
    const assistantMsg: ChatMessage = {
      role: 'assistant',
      content: '',
      metadata: undefined
    };
    this.messages.push(assistantMsg);
    
    this.$nextTick(() => this.scrollToBottom());
    
    this.currentAnswer = '';
    let processedQuery = this.inputText;
    this.inputText = '';

    if (this.data) {
      processedQuery += " 基于下列数据进行分析：" + JSON.stringify(this.data);
    }

    // 答案映射处理
    for (const item of this.answerMap) {
      if (processedQuery.includes(item.name)) {
        processedQuery = processedQuery.replace(item.name, item.value);
        break;
      }
    }

    const request = {
      query: processedQuery,
      response_mode: "streaming",
      conversation_id:'',
      inputs:{},
      user: "user-" + Date.now(), // 更严谨的用户标识
      files: this.data ? [{
        type: 'custom',
        transfer_method: 'local_file',
        upload_file_id: this.data.id // 假设已上传文件
      }] : []
    };

    try {
      await this.fetchLocalStream(request);
    } finally {
      this.loading = false;
    }
  }

  private handleStreamData(chunk: string) {
    this.currentAnswer += chunk;
    
    // 更新最后一条消息
    this.messages = [
      ...this.messages.slice(0, -1),
      {
        ...this.messages[this.messages.length - 1],
        content: this.currentAnswer
      }
    ];
    
    this.scrollToBottom();
  }

  scrollToBottom() {
      if(this.scroll.wrap$ &&  this.scroll.wrap$.scrollHeight){
        this.scroll.wrap$.scrollTop = this.scroll.wrap$.scrollHeight;
      }
    }

  private handleStreamMeta(meta: any) {
    // 更新元数据到当前消息
    const lastMsg = this.messages[this.messages.length - 1];
    if (lastMsg) {
      lastMsg.metadata = meta;
    }
  }

  private handleStreamFile(file: any) {
    // 处理文件类型消息
    const lastMsg = this.messages[this.messages.length - 1];
    if (lastMsg) {
      lastMsg.files = lastMsg.files || [];
      lastMsg.files.push({
        type: file.type,
        url: file.url
      });
    }
  }

  mounted() {
    this.streamDataHandler = (chunk: string) => this.handleStreamData(chunk);
    this.streamMetaHandler = (meta: any) => this.handleStreamMeta(meta);
    this.streamFileHandler = (file: any) => this.handleStreamFile(file);
    
    this.$on('stream-data', this.streamDataHandler);
    this.$on('stream-meta', this.streamMetaHandler);
    this.$on('stream-file', this.streamFileHandler);

    (this as any).$bus.$on('data', (data: any) => {
      this.data = data;
    });
  }

  beforeDestroy() {
    this.$off('stream-data', this.streamDataHandler);
    this.$off('stream-meta', this.streamMetaHandler);
    this.$off('stream-file', this.streamFileHandler);
    this.abortStream();
  }
  stopMessage(){
       
       this.abortStream();
       this.loading = false;
   }
}
</script>
  
  <style scoped lang="scss">
  .chat-container {
    height: 90vh;
    display: flex;
    flex-direction: column;
   
    background:url(~@/assets/image/banner-background.png) center center no-repeat; 
    /* 新增欢迎信息样式 */
  .welcome-message {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    padding: 20px;
    height: 100%;

    .welcome-title {
      color: #1a73e8; /* 主标题蓝色 */
      font-size: 24px;
      margin-bottom: 16px;
      font-weight: 500;
    }

    .welcome-subtitle {
      color: #606266; /* 副标题深灰色 */
      font-size: 16px;
      line-height: 1.6;
      max-width: 600px;
      opacity: 0.9;
    }
  }
  
.messages-box {
      flex: 1;
      padding: 20px;
  
      .message {
        margin-bottom: 16px;
  
        &.user {
          margin-left: 20%;
          .el-card {
            background: #f0f7ff;
          }
        }
  
        &.assistant {
          margin-right: 20%;
          .el-card {
            background: #f5f7fa;
          }
        }
  
        .message-header {
          margin-bottom: 8px;
        }
      }
  
      .loading-indicator {
        text-align: center;
        color: #909399;
        padding: 10px;
      }
    }
}

/* 容器定位 */
.input-with-buttons {
  position: relative;  /* 关键：为按钮定位提供基准 */
}

/* 输入框样式 */
.input-box {
  padding-right: 120px !important; /* 给右侧按钮预留空间 */
  ::v-deep .el-textarea__inner {
    resize: vertical;  /* 允许垂直调整高度 */
  }
}

/* 内部按钮容器 */
.inner-buttons {
  position: absolute;
  right: 10px;
  bottom: 10px;
  z-index: 2;  /* 确保按钮在输入框上方 */
  display: flex;
  gap: 8px;    /* 按钮间距 */
  
  /* 适配输入框高度变化 */
  transition: bottom 0.2s;
}

/* 当输入框高度变化时微调按钮位置 */
::v-deep .el-textarea__inner:focus {
  & + .inner-buttons {
    bottom: 12px;  /* 聚焦时微调位置 */
  }
}

/* 按钮悬停效果 */
.inner-buttons .el-button {
  opacity: 0.9;
  transition: opacity 0.2s;
  &:hover {
    opacity: 1;
    transform: translateY(-1px);
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .inner-buttons {
    right: 6px;
    bottom: 6px;
    gap: 6px;
  }
  
  .input-box {
    padding-right: 100px !important;
  }
  
  .inner-buttons .el-button {
    padding: 8px 12px;
  }
}
  </style>